<script setup lang="ts">
import type {
  PlusColumn,
  FieldValues,
  OptionsRow,
  PlusFormGroupRow
} from "plus-pro-components";
import {
  PlusDialogForm,
  PlusCheckCardGroup,
  PlusDialogFormInstance
} from "plus-pro-components";
import { useColumns } from "./columns";
import { computed, Fragment, h, onMounted, reactive, ref, unref } from "vue";
import { FlowerMaterial, FlowerOccasion, FlowerReceiver } from "@/constants";
import { getFlowerOptions, getFlowerTypeOptions } from "@/api/flower";
import { ElUpload, ElImage, ElScrollbar, FormInstance } from "element-plus";
import { IconifyIconOnline } from "@/components/ReIcon";
import {
  getAppConfig,
  getWexinTodayRecommend,
  updateAppConfig
} from "@/api/config";
import { TodayRecommendItem } from "types/app-config";
import { message } from "@/utils/message";
import { FlowerOptionItem } from "types/flower";
import { nextTick, title } from "process";
import { cloneDeep } from "@pureadmin/utils";

const SERVER_URL = import.meta.env.VITE_SERVER_URL;

const state = reactive({
  loading: false,
  submitting: false
});

const dataList = ref<TodayRecommendItem[]>();

const flowerOptions = ref<{ title: string; value: number }[]>([]);
let flowerMap: Record<number, FlowerOptionItem> = [];

const loadFlowerOptions = async () => {
  try {
    const response = await getFlowerOptions();
    flowerOptions.value = response.map(item => ({
      title: item.name,
      value: item.id,
      avatar: () => {
        if (item.images && item.images.length > 0) {
          return h("img", {
            src: SERVER_URL + item.images[0],
            style:
              "width:128px; height:64px; object-fit:contain; display:block;"
          });
        } else {
        }
        return h("img", {
          src: "/images/flower.png",
          style: "width:128px; height:64px; object-fit:contain; display:block;"
        });
      },

      description: () => h("p", {}, `￥${item.price}`)
    }));
    flowerMap = response.reduce((map, item) => {
      map[item.id] = item;
      return map;
    }, {});
  } catch (error) {
    console.log(error);
  }
};

const { columns } = useColumns({
  onEdit: (row, index) => {
    itemIndex.value = index;
    formData.value = {
      id: row.id,
      title: row.title,
      tag: row.tag,
      flower_id: row.flower_id
    };
    formVisible.value = true;
  },
  onDelete: async (_, index) => {
    try {
      const data = cloneDeep(dataList.value);

      data.splice(index, 1);
      await updateAppConfig({
        name: "weixin-today-recommend",
        data: data.map(item => ({
          id: item.id,
          flower_id: item.flower_id,
          title: item.title,
          tag: item.tag
        }))
      });
      message("删除成功", { type: "success" });
      loadData();
    } catch (e) {
      if (e.response.data && e.response.data.message) {
        message(e.response.data.message, { type: "error" });
      } else {
        message("删除失败", { type: "error" });
      }
      console.log(e);
    }
  },
  onRowDrop: ({ newIndex, oldIndex }) => {
    const currentRow = dataList.value.splice(oldIndex, 1)[0];
    dataList.value.splice(newIndex, 0, currentRow);

    updateAppConfig({
      name: "weixin-today-recommend",
      data: dataList.value.map((item, index) => ({
        id: item.id,
        flower_id: item.flower_id,
        title: item.title,
        tag: item.tag
      }))
    }).finally(() => {
      loadData();
    });
  }
});

const loadData = async () => {
  try {
    state.loading = true;
    const response = await getWexinTodayRecommend();
    dataList.value = response;
    console.log(response);
    state.loading = false;
  } catch (error) {
    console.log(error);
  }
};

onMounted(async () => {
  await loadFlowerOptions();
  loadData();
});

const formRules = {
  title: [
    {
      required: true,
      message: "请输入标题"
    }
  ],
  tag: [
    {
      required: true,
      message: "请输入标签"
    }
  ],
  flower_id: [
    {
      required: true,
      message: "请选择鲜花"
    }
  ]
};
const itemIndex = ref<number | null>(null);
const formVisible = ref(false);
const formRef = ref<PlusDialogFormInstance | null>(null);
const formData = ref<FieldValues>({ status: 1 });
const formColumns: PlusColumn[] = [
  {
    label: "标题",
    width: 120,
    prop: "title",
    valueType: "input"
  },
  {
    label: "标签",
    prop: "tag",
    valueType: "input"
  },
  {
    label: "鲜花",
    prop: "flower_id",
    renderField(value: string, onChange) {
      return h(Fragment, [
        h(
          ElScrollbar,
          { height: 400 },
          h(PlusCheckCardGroup, {
            modelValue: value,
            options: flowerOptions.value,
            onChange: e => {
              onChange(e);
              nextTick(() => {
                formRef.value.formInstance.validateField(["flower_id"]);
              });
            }
          })
        )
      ]);
    }
  }
];

const handleNew = () => {
  itemIndex.value = null;
  formData.value = {};
  formVisible.value = true;
};

const handleConfirm = async e => {
  try {
    state.submitting = true;
    if (itemIndex.value === null) {
      await updateAppConfig({
        name: "weixin-today-recommend",
        data: [
          ...dataList.value.map((item, index) => ({
            id: index + 1,
            flower_id: item.flower_id,
            title: item.title,
            tag: item.tag
          })),
          {
            ...e,
            id: dataList.value.length + 1
          }
        ]
      });
    } else {
      const data = cloneDeep(dataList.value);

      data[itemIndex.value] = {
        ...data[itemIndex.value],
        id: e.id,
        flower_id: e.flower_id,
        title: e.title,
        tag: e.tag
      };

      await updateAppConfig({
        name: "weixin-today-recommend",
        data: data.map(item => ({
          id: item.id,
          flower_id: item.flower_id,
          title: item.title,
          tag: item.tag
        }))
      });
    }

    message("保存成功", { type: "success" });
    formVisible.value = false;
    loadData();
  } catch (e) {
    if (e.response.data && e.response.data.message) {
      message(e.response.data.message, { type: "error" });
    } else {
      message("保存失败", { type: "error" });
    }
    console.log(e);
  } finally {
    state.submitting = false;
  }
};
</script>

<template>
  <div>
    <el-card shadow="never">
      <template #header>
        <div class="flex justify-between items-center">
          <span>今日推荐</span>

          <el-space>
            <el-button type="primary" @click="handleNew">
              <template #icon>
                <IconifyIconOnline icon="ep:plus" />
              </template>
              新增
            </el-button>
          </el-space>
        </div>
      </template>
      <pure-table
        border
        adaptive
        row-key="id"
        :loading="state.loading"
        :data="dataList"
        :columns="columns"
      />
    </el-card>
    <PlusDialogForm
      ref="formRef"
      v-model:visible="formVisible"
      v-model="formData"
      :destroy-on-close="true"
      :title="itemIndex ? '修改' : '添加'"
      :form="{
        columns: formColumns,
        rules: formRules,
        labelPosition: 'top',
        rowProps: {
          gutter: 12
        }
      }"
      :confirmLoading="state.submitting"
      @confirm="handleConfirm"
    />
  </div>
</template>
<style scoped lang="scss">
:deep(.swiper-upload) {
  .el-upload--picture-card {
    width: 320px;
    overflow: hidden;
  }
}
:deep(.plus-check-card) {
  padding-block: 12px;
  padding-inline: 0;
}
</style>
